#include "qthreadwrapper.h"

#ifdef _SYMBIAN

#include <QObject>

class SymbianTimer : public QObject
{
public:
    SymbianTimer(ThreadFunction func, ThreadArgument arg):
        m_threadFunction(func),
        m_threadArgument(arg)
    {
    }

    void timerEvent(QTimerEvent* event)
    {
        m_threadFunction(m_threadArgument);
    }

    void setTimerID(int id)
    {
        m_timerID = id;
    }

    inline int getTimerID() const
    {
        return m_timerID;
    }

private:
    ThreadFunction m_threadFunction;
    void* m_threadArgument;
    int m_timerID;
};

Thread createThread(ThreadFunction func, ThreadArgument arg)
{
    SymbianTimer* timer = new SymbianTimer(func, arg);

    int id = timer->startTimer(10);
    timer->setTimerID(id);

    return timer;
}

void sleepThread(Thread thread, unsigned long usec)
{
}

void destroyThread(Thread thread)
{
    Q_ASSERT(thread);

    SymbianTimer* timer = (SymbianTimer*)thread;
    timer->killTimer(timer->getTimerID());
}

#else

#include <QThread>
#include "qDebugWrapper.h"

// QThread Implementation
class ThreadIpml : public QThread
{
public:
    ThreadIpml(ThreadFunction func, ThreadArgument arg):
        QThread(0),
        m_threadFunction(func),
        m_threadArgument(arg)
    {}

    void run()
    {
        m_threadFunction(m_threadArgument);
    }

    void sleep(unsigned long usec)
    {
        QThread::usleep(usec);
    }

private:
    ThreadFunction m_threadFunction;
    void* m_threadArgument;
};


Thread createThread(ThreadFunction func, ThreadArgument arg)
{
    ThreadIpml* qThread = new ThreadIpml(func, arg);
    qThread->start(QThread::NormalPriority);

    return (Thread)qThread;
}

void sleepThread(Thread thread, unsigned long usec)
{
    ThreadIpml* qThread = (ThreadIpml*)thread;
    qThread->sleep(usec);
}

void destroyThread(Thread thread)
{
    Q_ASSERT(thread);

    ThreadIpml* qThread = (ThreadIpml*)thread;

    if (!qThread->wait())
    {
        Q_PRINT("Timeout! Terminating...");
        qThread->terminate();
    }
}
#endif
